import { useState, useRef, useEffect } from 'react'
import { getData } from '@/api/test.js'

/**
 * React 总是在执行下一轮渲染的 Effect 之前清理上一轮渲染的 Effect。
 * 所谓清理上一轮渲染的 Effect 就是调用 return 方法
 */

function Map() {
  const [zoomLevel] = useState(1)
  const mapRef = useRef(null)
  useEffect(() => {
    mapRef.current.setAttribute['data-zoom'] = zoomLevel // 允许执行两次，不需要进行 "清理"
    console.log('连接中。。。')

    function handleScorll() {
      //   console.log(window.scrollX, window.scrollY)
    }
    window.addEventListener('scroll', handleScorll)
    document.querySelector('#test').focus()
    return () => {
      console.log('断开连接。。。')

      window.removeEventListener('scroll', handleScorll)
    }
  }, [zoomLevel])
  return (
    <div ref={mapRef} data-zoom={zoomLevel} style={{ height: '600px' }}>
      1
    </div>
  )
}

export default function App() {
  const [person, setPerson] = useState('1')
  const [bio, setBio] = useState(null)

  useEffect(() => {
    let ignore = false
    setBio(null)
    getData(person).then((result) => {
      if (!ignore) {
        console.log(result)
        setBio(result.id)
      }
    })
    return () => {
      ignore = true
    }
  }, [person])
  return (
    <div>
      <Map />
      <input id="test" />
      <div style={{ height: '200px', padding: '20px', backgroundColor: 'red' }}></div>
      <select
        value={person}
        onChange={(e) => {
          setPerson(e.target.value)
        }}
      >
        <option value="1">Alice1</option>
        <option value="2">Bob2</option>
        <option value="3">Taylor3</option>
      </select>
      <hr />
      <p>
        <i>{bio ?? '加载中……'}</i>
      </p>
    </div>
  )
}
